/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Downloader;

import Interface.AVideoDownloader;
import Manager.DownloaderManager;
import java.io.File;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author wcss
 */
public class QvodDownloader extends AVideoDownloader implements Runnable {

    public static String qvodSourceFile = "/opt/qvoddownloadtool/sq_hide_compress.exe";
    public static long qvodSourceLength = 544 * 1024;
    public static int qvodTimeout = 600;
    public static String runScript = "wine (File)";
    public String qvodWorkDir = "";
    public String qvodShellFile = "";
    public long movieFileLength = 0;
    private Thread workThread = null;
    private Boolean isRun = false;
    private int runTime = 0;
    private Process qvodProcess = null;
    private long lastReportLength = 0;
    public boolean isTaskFinish = false;
    public String qvodStateStr = "";
    private long baseMovieProgress = 0;
    private long qvodShellFileLength = 0;
    Boolean showInitInfo = true;
    InputStream readQvodStateStream = null;
    int waitcount = 0;
    String waitstrs = "";

    public QvodDownloader() {
        this.downloadType = "qvod";
    }

    /**
     * 获取下载影片目录名
     *
     * @param qvodurl
     * @return
     */
    public String getDownLoadMovieStr(String qvodurl) {
        String url = qvodurl.replace("qvod://", "");
        String[] ext = url.split("\\|")[2].split("\\.");
        return url.split("\\|")[1] + "+" + url.split("\\|")[0] + "." + ext[ext.length - 1];
    }

    /**
     * 获取下载影片名
     *
     * @param qvodurl
     * @return
     */
    public String getMovieStr(String qvodurl) {
        String url = qvodurl.replace("qvod://", "");
        return url.split("\\|")[2];
    }

    /**
     * 获取下载影片HashCode
     *
     * @param qvodurl
     * @return
     */
    public String getHashStr(String qvodurl) {
        String url = qvodurl.replace("qvod://", "");
        return url.split("\\|")[1];
    }

    /**
     * 获取下载影片长度
     *
     * @param qvodurl
     * @return
     */
    public long getMovieLength(String qvodurl) {
        String url = qvodurl.replace("qvod://", "");
        return Long.parseLong(url.split("\\|")[0]);
    }

    /**
     * 获取Qvod下载工具长度
     *
     * @return
     */
    public long getQvodShellLength() {
        return DownloaderManager.getDirUseSize(this.qvodShellFile);
    }

    /**
     * 获取当前下载大小
     *
     * @return
     */
    public long getCurrentLength() {
        long curlength = DownloaderManager.getDirUseSize(this.qvodWorkDir);
        curlength = curlength - qvodShellFileLength;
        return curlength;
    }

    /**
     * 获取临时文件
     *
     * @return
     */
    public String getMovieFileName() {
        String result = "";
        File dir = new File(this.qvodWorkDir);
        File[] files = dir.listFiles();
        for (File f : files) {
            if (!f.getName().toLowerCase().contains(".exe")) {
                result = f.getName();
                break;
            }
        }

        return result;
    }

    @Override
    public void clearBufferDir() {
        try {
            JAppToolKit.JRunHelper.runSysCmd("rm -rf " + this.qvodWorkDir);
        } catch (Exception ex) {
            Logger.getLogger(QvodDownloader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void open(String videourl) throws Exception {
        this.videoUrl = videourl;
        boolean result = isValidUrl(this.videoUrl);
        if (result) {
            qvodWorkDir = JAppToolKit.JRunHelper.getUserHomeDirPath() + "/.qvodcache/" + getHashStr(this.videoUrl) + "_" + getDownLoadMovieStr(this.videoUrl);
            this.videoBufferUrl = qvodWorkDir + "//" + getDownLoadMovieStr(this.videoUrl);
            qvodShellFile = qvodWorkDir + "//" + getDownLoadMovieStr(this.videoUrl) + "_" + getHashStr(this.videoUrl) + ".exe";
            //System.out.println(qvodWorkDir);
            //System.out.println(movieFile);
            //System.out.println(qvodShellFile);
            qvodShellFileLength = getQvodShellLength();
            this.movieFileLength = this.getMovieLength(this.videoUrl);
            isTaskFinish = false;
            File base = new File(qvodWorkDir);
            if (!base.exists()) {
                base.mkdirs();
            }
            //File copy = new File(DownLoader.qvodSourceFile);           
            //jAppHelper.jCmdRunHelper.runSysCmd("cp " + DownLoader.qvodSourceFile + " " + qvodShellFile);
            DownloaderManager.copyFile(QvodDownloader.qvodSourceFile, qvodShellFile);
            qvodStateStr = "初始化完成";
        } else {
            throw new Exception("This Url is not download!");
        }
    }

    @Override
    public int getMaxDownloadSpeed() {
        return -1;
    }

    @Override
    public int getMaxUploadSpeed() {
        return -1;
    }

    @Override
    public void setMaxDownloadSpeed(int speed) {
    }

    @Override
    public void setMaxUploadSpeed(int speed) {
    }

    @Override
    public Boolean isRunning() {
        return isRun;
    }

    @Override
    public Boolean isValidUrl(String url) {
        if (url != null) {
            if (url.startsWith("qvod:") && url.endsWith("|")) {
                String[] team = url.split("|");
                if (team.length >= 3) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 运行下载器
     *
     * @throws Exception
     */
    public void runQvodProgram() throws Exception {
        String downloadcmd = QvodDownloader.runScript.replace("(File)", this.qvodShellFile);
        qvodProcess = JAppToolKit.JRunHelper.runSysCmd(downloadcmd, false);
    }

    @Override
    public void start() throws Exception {
        if (workThread == null) {
            isRun = true;
            runTime = 0;
            workThread = new Thread(this);
            workThread.setDaemon(true);
            runQvodProgram();
            workThread.start();
            qvodStateStr = "任务已经开始";
            showInitInfo = true;
            baseMovieProgress = this.getCurrentLength();
        }
    }

    @Override
    public void stop() throws Exception {
        this.isRun = false;
        if (qvodProcess != null) {
            qvodProcess.destroy();
            JAppToolKit.JRunHelper.runSysCmd("killall " + new File(this.qvodShellFile).getName());
            qvodStateStr = "任务已经停止";
        }
    }

    public void dispose() {
        if (this.workThread != null) {
            this.workThread.stop();
            workThread = null;
        }
    }

    @Override
    public long getTotalSize() {
        return getMovieLength(this.videoUrl);
    }

    @Override
    public long getCurSize() {
        return this.getCurrentLength();
    }

    @Override
    public int getDownloadProgress() {
        return (int) (((double)this.getCurSize() / (double)this.getTotalSize()) * 100);
    }

    @Override
    public int getDownloadSpeed() {
        return 100;
    }

    @Override
    public String getVideoShowName() {
        return this.getMovieStr(this.videoUrl);
    }

    @Override
    public AVideoDownloader getNewDownloader() {
        return new QvodDownloader();
    }

    private void onReadQvodStates() {
        if (showInitInfo) {
            if (waitcount < 3) {
                waitcount++;
            } else {
                waitcount = 1;
                waitstrs = ".";
            }
            for (int k = 0; k < waitcount; k++) {
                waitstrs += ".";
            }
            this.qvodStateStr = "正在搜索地址" + waitstrs;
            this.onReportStatus("showinfo:" + this.qvodStateStr);
        } else {
            waitcount = 0;
        }
    }

    @Override
    public void run()
    {
        while(isRun)
        {
            try {
                Thread.sleep(1000);
                
                this.onReadQvodStates();
                
                runTime++;
                //check movie progress
                long current = this.getCurrentLength();
                //report movie progress
                if (current != lastReportLength)
                {
                   if (current > baseMovieProgress)
                   {
                      qvodStateStr = "任务正在下载";
                      showInitInfo = false;
                      lastReportLength = current;
                      runTime = 0;
//                      checkMovieLength();
                      onReportProgress(current);
                   }else
                   {
                       //进度不正确
                   }
                }
                //if download finish then close thread
                if (current >= this.movieFileLength)
                {
                   qvodStateStr = "任务已完成";
                   isTaskFinish = true;
                   this.stop();
                   onReportFinish(); 
                }else if (current == lastReportLength && runTime >= QvodDownloader.qvodTimeout)
                {
                   this.stop();
                   onReportError("downloadtimeout","Download Timeout!");
                }
            } catch (Exception ex)
            {
                ex.printStackTrace();
                onReportError("runningerror",ex.toString());
            }           
        }
    }

    @Override
    public String getVideoBufferUrl() 
    {
        if (getMovieFileName().equals(""))
        {
            return this.videoBufferUrl;
        }else
        {
            return this.qvodWorkDir + "/" + getMovieFileName();
        }
    }
}
